#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import sc2reader 
import sc2reader.objects
import sc2reader.resources
import sc2reader.data
import sc2reader.events
import inspect
from sc2reader import SC2Reader
from ugly_lookup import TOSS_LOOKUP
from ugly_lookup import * 

import dircache

SUPPLY_BUCKETS = 6
def do(path):
    print "Beginning process"
    game_id = 0
    GAME_DB_HANDLE = open( "GAME_DB.txt", "w")
    replays = set()
    file_list = dircache.listdir(path)

    for file in file_list:
        replay = SC2Reader().load_replay( "{0}\{1}".format( path, file ) )
        
        game_id = game_id+1
        
        print "Release {0}".format(replay.release_string)
        print "{0} on {1}".format(replay.type,replay.map)
        by_player = {}
        for player in replay.players:
            by_player[player] = {0:4,1:'',2:'',3:0,4:0,5:"",6:""}
            print player
        print "\n--------------------------\n\n"
        
        events = replay.events
        # Loop through the events
        lookup = TOSS_LOOKUP.copy()
        
        empty_bcode = BCode('UNKNOWN','')
        
        
        for event in events:
            if( isinstance( event, sc2reader.events.AbilityEvent ) ):
               
                build_code = lookup[event.ability] if event.ability in lookup else empty_bcode
                if not event.ability in lookup : continue
                
                
                player = event.player
                target = event.target if hasattr(event, 'target') else ""
                location = event.location if hasattr( event, 'location') else ""
                
                latest_ability = by_player[player][3]
                latest_time = by_player[player][4]
                latest_location = by_player[player][5]
                latest_target = by_player[player][6]
                
                is_suspected_dupe = False 
                if( event.ability == latest_ability and ( event.time.seconds - latest_time )<= 2 ):
                    is_suspected_dupe = True
                else:
                    is_suspected_dupe = False
                    by_player[player][3] = event.ability
                    by_player[player][4] = event.time.seconds 
                    by_player[player][5] = target
                    by_player[player][6] = location 
                                    
                
                # I think bucketing by food is better than time
                food = TOSS_FOOD_LOOKUP[build_code.code] if build_code.code in TOSS_FOOD_LOOKUP else 0
                old_food = by_player[player][0] 
                new_food = old_food + food
                
                bo_addition = build_code.code if not event.ability in TOSS_EXCLUDE_LIST else ''
                if( not is_suspected_dupe ):
                    by_player[player][0] = new_food
                    by_player[player][1] += bo_addition
                    if old_food / SUPPLY_BUCKETS != new_food / SUPPLY_BUCKETS:
                        by_player[player][1] += " {0} {1} ".format( new_food, event.time.seconds)
                
                by_player[player][2] += "{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}\r".format( event.time.seconds, player.name, hex( event.ability ), build_code.text, food, target, location, is_suspected_dupe)
                
                #food check
                if by_player[player][0]  >= 60: break
                
        build_file_format = "parsed\\BO.{0}.{1}.txt"
        for player in replay.players:
                        
            BO_HANDLE = open( build_file_format.format(game_id,player.name), "w")
            BO_HANDLE.write( "Release {0}\r".format(replay.release_string) )
            for player2 in replay.players:
                BO_HANDLE.write( str( player2 ) + "\r" )
            BO_HANDLE.write( "Winner {0}\r".format( replay.winner.number ) )
            BO_HANDLE.write( 'ENCODING to 60 SUPPLY:\r  ' )
            BO_HANDLE.write( by_player[player][1] +"\r" )
            BO_HANDLE.write( 'BEGIN DUMP\r' )
            BO_HANDLE.write( by_player[player][2] +"\r" )
            
            BO_HANDLE.flush()
            BO_HANDLE.close()
            if len(by_player[player][1]) >0:
                GAME_DB_HANDLE.write("{0}:{1}:{2}\r".format( game_id, player.name, by_player[player][1] ) )
            
            
    GAME_DB_HANDLE.flush()
    GAME_DB_HANDLE.close()
    
if __name__ == '__main__':

    do(sys.argv[1])
